﻿using FasterWPF;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using Xceed.Wpf.DataGrid;

namespace FasterWPFExtras
{
    public static class XceedGridExt
    {
        public static void Initialize(this Xceed.Wpf.DataGrid.DataGridControl dgc, double width, double height, DataSet ds)
        {
            dgc.AutoCreateColumns = true;
            dgc.Width = width;
            dgc.Height = height;
            dgc.SelectionMode = System.Windows.Controls.SelectionMode.Single;

            StyleExt.SetStyle(dgc, typeof(GroupByControl), GroupByControl.AllowGroupingModificationProperty, false, GroupByControl.VisibilityProperty, Visibility.Collapsed);
            StyleExt.SetStyle(dgc, typeof(ColumnManagerRow), ColumnManagerRow.HeightProperty, 30D);

            DataGridCollectionView myCollectionView;
            myCollectionView = new DataGridCollectionView(ds.Tables[0].DefaultView);

            dgc.ItemsSource = myCollectionView;

            dgc.RetriveDataRows().ForEach(drv => { drv.Row.AcceptChanges(); });
        }

        public static void AddNewRow(this Xceed.Wpf.DataGrid.DataGridControl dgc)
        {
            ((DataGridCollectionView)dgc.ItemsSource).AddNew();
            ((DataGridCollectionView)dgc.ItemsSource).CommitNew();

            int count = ((DataGridCollectionView)dgc.ItemsSource).SourceItems.Count;

            if (dgc.CurrentItem != null)
            {
                Xceed.Wpf.DataGrid.DataRow row = dgc.GetContainerFromItem(dgc.CurrentItem) as Xceed.Wpf.DataGrid.DataRow;
                if (row != null)
                {
                    DataGridCommands.EndEdit.Execute(null, row);
                }
            }

            dgc.SelectedItems.Clear();
            dgc.SelectedItems.Add(dgc.Items[count-1]);
        }

        public static void DeleteSelectedRow(this Xceed.Wpf.DataGrid.DataGridControl dgc)
        {      
            if(dgc.CurrentItem!=null)
            {
                Xceed.Wpf.DataGrid.DataRow row = dgc.GetContainerFromItem(dgc.CurrentItem) as Xceed.Wpf.DataGrid.DataRow;
                if (row != null)
                {
                    DataGridCommands.EndEdit.Execute(null, row);
                }
            }

            MessageBoxResult result = System.Windows.MessageBox.Show("Are you certain you want to delete the selected rows?", "Confirm Delete", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                if(dgc.SelectedItem!=null)
                {
                   ((DataGridCollectionView)dgc.ItemsSource).Remove(dgc.SelectedItem);
                   ((DataGridCollectionView)dgc.ItemsSource).CommitNew();
                }
            }    
        }

        public static void DeleteSelectedRow(this Xceed.Wpf.DataGrid.DataGridControl dgc, Action actionToPerformOnDelete)
        {
            if (dgc.CurrentItem != null)
            {
                Xceed.Wpf.DataGrid.DataRow row = dgc.GetContainerFromItem(dgc.CurrentItem) as Xceed.Wpf.DataGrid.DataRow;
                if (row != null)
                {
                    DataGridCommands.EndEdit.Execute(null, row);
                }
            }

            MessageBoxResult result = System.Windows.MessageBox.Show("Are you certain you want to delete the selected rows?", "Confirm Delete", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                if (dgc.SelectedItem != null)
                {
                    ((DataGridCollectionView)dgc.ItemsSource).Remove(dgc.SelectedItem);
                    ((DataGridCollectionView)dgc.ItemsSource).CommitNew();

                    actionToPerformOnDelete();
                }
            }
        }

        public static List<DataRowView> RetriveDataRows(this Xceed.Wpf.DataGrid.DataGridControl dgc)
        {
            if(dgc.CurrentItem!=null)
            {
                 Xceed.Wpf.DataGrid.DataRow row = dgc.GetContainerFromItem(dgc.CurrentItem) as Xceed.Wpf.DataGrid.DataRow;
                 if (row != null)
                 {
                      DataGridCommands.EndEdit.Execute(null, row);
                 }
            }

            List<DataRowView> drvList=new List<DataRowView>();
            
            foreach (object zx in((DataGridCollectionView)dgc.ItemsSource).SourceItems) //XceedGrid.ItemsSource)
            {      
               drvList.Add(zx as DataRowView);
            }

            return drvList;
        }

        public static List<DataRowView> ValidateRows(this Xceed.Wpf.DataGrid.DataGridControl dgc, int errorColumn, Predicate<DataRowView> pred, string validationErrorMessage)
        {
            if (dgc.CurrentItem != null)
            {
                Xceed.Wpf.DataGrid.DataRow row = dgc.GetContainerFromItem(dgc.CurrentItem) as Xceed.Wpf.DataGrid.DataRow;
                if (row != null)
                {
                    DataGridCommands.EndEdit.Execute(null, row);
                }
            }

            List<DataRowView> drvList = new List<DataRowView>();

            foreach (object zx in ((DataGridCollectionView)dgc.ItemsSource).SourceItems) //XceedGrid.ItemsSource)
            {
                if (pred(zx as DataRowView))
                {
                    (zx as DataRowView).Row[errorColumn] = validationErrorMessage;
                }
                else
                {
                    if ((zx as DataRowView).Row[errorColumn] != DBNull.Value)
                    {
                        (zx as DataRowView).Row[errorColumn] = String.Empty;
                    }
                }
            }

            return drvList;
        }
        //validate grid
    }
}


#region code for using entity instead of dataset
//ObservableCollection<Person> people = new ObservableCollection<Person>();
//people.Add( new Person( "Jenny", "Beland" ) );
//people.Add( new Person( "Francois", "Carignan" ) );
//people.Add( new Person( "Jacques", "Bourque" ) );
//people.Add( new Person( "Pascal", "Bourque" ) );
//people.Add( new Person( "Marc", "Laroche" ) );
//people.Add( new Person( "Pierre-Luc", "Ledoux" ) );
//people.Add( new Person( "Catherine", "Sauzede" ) );
//people.Add( new Person( "Christian", "Nadeau" ) );
//DataGridCollectionView collectionView = new DataGridCollectionView( people, typeof( Person ) );
//dataGridControl.ItemsSource = collectionView;
//    private void CollectionView_CreatingNewItem( object sender, DataGridCreatingNewItemEventArgs e )
//{
// e.NewItem = new Person( Person.AutoIncrementID, string.Empty, string.Empty, -1 );
// e.Handled = true;
//}
//private void CollectionView_CommittingNewItem( object sender, DataGridCommittingNewItemEventArgs e )
//{
// List<Person> source = e.CollectionView.SourceCollection as List<Person>;
// source.Add( ( Person )e.Item );
// Person.AutoIncrementID = Person.AutoIncrementID + 1;
// // the new item is always added at the end of the list.     
// e.Index = source.Count - 1;
// e.NewCount = source.Count;
// e.Handled = true;
//}
//private void CollectionView_CancelingNewItem( object sender, DataGridItemHandledEventArgs e )
//{
// // Manually handling the insertion of new items requires that the CreatingNewItem,
// // CommitingNewItem, and CancelingNewItem events must all be handled even if nothing
// // is done in the event.
// e.Handled = true;
//}
#endregion